package com.netease.yunxin.kit.chatkit.ui.share

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.netease.yunxin.kit.chatkit.ui.R

class ShareFileAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    val dataList = mutableListOf<String>()
    var itemClick: ((String) -> Unit)? = null

    fun setData(datas: MutableList<String>) {
        dataList.clear()
        dataList.addAll(datas)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return ShareFileViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.adapter_item_share_file, null)
        )
    }

    override fun getItemCount(): Int {
        return dataList.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is ShareFileViewHolder) {
            holder.tvName.text = getFileName(dataList[position])
            holder.itemView.setOnClickListener {
                itemClick?.invoke(dataList[position])
            }
        }
    }

    /**
     * 截取路径中最后一个“/”后的内容
     *
     * @param path-传入的完整路径
     * @return 文件名
     */
    fun getFileName(path: String): String? {
        val separatorIndex = path.lastIndexOf("/")
        return if (separatorIndex < 0) path else path.substring(
            separatorIndex + 1, path.length
        )
    }

    class ShareFileViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var tvName: TextView

        init {
            tvName = itemView.findViewById(R.id.tvName)

        }
    }

}
